let city = ''
$.ajax({
  url: "../city.json",
  data: { action: "jQueryAjax" },
  type: "GET",
  async: false,
  success: function (data) {
    city = data
  },
  //返回数据的格式
  dataType: "json"
})
const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      rules: {
        Supplier_Name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        Tax_Number: [{ required: true, message: '请输入纳税识别号', trigger: 'blur' }],
        selectProvince: [{ required: true, message: '请选择供应商地址', trigger: 'blur' }],
      },
      Bank_Name: [{ required: true, message: '请输入供应商开户银行', trigger: 'blur' }],
      Account_Number: [{ required: true, message: '请输入供应商银行账号', trigger: 'blur' }],
      // 整个省市县数据
      city: city,
      // 被选中的市数据
      cityList: [],
      // 被选中的县数据
      areaList: [],
      isdisabled: true,
      selectProvince: {},
      selectCity: {},
      brand: [],
      article: [],
      selectArea: {},
      address: '',
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      form: {
        Supplier_SerialNumber: '',
        Supplier_Name: '',
        Tax_Number: '',
        Supplier_Address: '',
        Enterprise_Info_SerialNumber: '',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          supplier_brand: [{       //供应商经营品牌
            Supplier_Brand_SerialNumber: "",
            Supplier_SerialNumber: '',
            Brand_SerialNumber: '',
          }],
          supplier_article: [{       //供应商可供商品
            Supplier_Article_SerialNumber: "",
            Supplier_SerialNumber: '',
            Article_SerialNumber: '',
          }],
          supplier_bank_account: [{       //供应商银行账号
            Supplier_Bank_Account_SerialNumber: "",
            Supplier_SerialNumber: '',
            Bank_Name: '',
            Account_Number: '',
          }],
          supplier_bank_pic: []
        }
      },
      loading: false,

    }
  },
  mounted() {
    const Supplier_SerialNumber = sessionStorage.getItem("Supplier_SerialNumber")
    this.getData(Supplier_SerialNumber);
  },
  methods: {
    getData(Supplier_SerialNumber) {
      const _this = this
      $.ajax({
        url: DomainName + '/getSupplierAction',
        type: 'POST',
        data: { Data: Supplier_SerialNumber, token: $.cookie("token") },
        success: function (res) {
          console.log('根据企业编号获取结果', res)
          _this.form = res.supplier_info[0]
          console.log(_this.form);
          let arr = _this.form.Supplier_Address.split('/')
          _this.selectProvince = _this.city.filter(item => {
            return item.label == arr[0]
          })[0]
          _this.cityList = _this.selectProvince.children
          _this.selectCity = _this.cityList.filter(item => {
            return item.label == arr[1]
          })[0]
          _this.areaList = _this.selectCity.children
          _this.selectArea = _this.areaList.filter(item => {
            return item.label == arr[2]
          })[0]
          _this.address = arr[3]
          _this.isdisabled = false
          _this.fileList.push(_this.form.Children.supplier_bank_pic[0])
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
      // 商品名称
      $.ajax({
        url: DomainName + '/GoodsFileInquiry',
        type: 'POST',
        data: {
          Data: "brand",
        },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          // console.log(res);
          for (let i = 0; i < res.length; i++) {
            let obj = {}
            obj.Brand_SerialNumber = res[i].Brand_SerialNumber;
            obj.Brand_Name = res[i].Brand_Name;
            _this.brand.push(obj);
          }
          // console.log(_this.brand);
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })

      $.ajax({
        url: DomainName + '/getInquiryAction',
        type: 'POST',
        data: {
          Data: "article_info",
          token: $.cookie("token")
        },
        success: function (res) {
          for (let i = 0; i < res.length; i++) {
            _this.article.push({
              Article_SerialNumber: res[i].Article_SerialNumber,
              Article_Name: res[i].Article_Name
            });
          }
          console.log(_this.article);
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })

    },
    //供应商相关材料照片
    upload(file) {
      let _this = this
      new Compressor(file, {
        quality: 0.08,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                if (Result.Status == "success") {
                  // _this.fileList[_this.fileList.length - 1].pic = e.target.result
                  _this.fileList.push({
                    Supplier_Bank_Pic_SerialNumber: '',
                    Supplier_SerialNumber: '',
                    Picture_Order: _this.fileList.length + 1,
                    Picture_Url: '',
                  })
                  _this.fileList[_this.fileList.length - 1].Picture_Url = Result.Picture_Url
                } else {
                  _this.$message.error(Result.msg)
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //查看图片
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file
    },
    //删除图片
    handleRemove(index) {
      this.fileList = this.fileList.filter(function (item) {
        return item.Picture_Order != index
      })
    },
    // 修改
    submitForm(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.fileList.forEach(function (item, index) {
            _this.form.Children.supplier_bank_pic[index].Picture_Url = item.Picture_Url
          })
          const { add, modify } = _this.deal()
          let data = {}
          if (add == null) {
            data = { Data: JSON.stringify({ Modify: { supplier_info: [modify] } }), token: $.cookie("token") }
          } else {
            data = {
              Data: JSON.stringify(
                {
                  Modify: { supplier_info: [modify] },
                  Add: { supplier_info: [add] }
                }
              ),
              token: $.cookie("token")
            }
          }
          _this.loading = true
          $.ajax({
            url: DomainName + '/getEditAction',
            type: 'POST',
            data,
            success: function (res) {
              console.log('提交结果', res)
              if (res.Status === 'success') {
                _this.$message.success("提交成功")
                window.history.go(-1)
              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_supplier_brand = [], modify_supplier_brand = []
      let add_supplier_bank_account = [], modify_supplier_bank_account = []
      let add_supplier_article = [], modify_supplier_article = []
      let add_supplier_bank_pic = [], modify_supplier_bank_pic = []
      for (const i in modify.Children.supplier_brand) {
        const obj = modify.Children.supplier_brand[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_supplier_brand.push(obj)
        } else {
          modify_supplier_brand.push(obj)
        }
      }
      for (const i in modify.Children.supplier_bank_account) {
        const obj = modify.Children.supplier_bank_account[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_supplier_bank_account.push(obj)
        } else {
          modify_supplier_bank_account.push(obj)
        }
      }
      for (const i in modify.Children.supplier_article) {
        const obj = modify.Children.supplier_article[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_supplier_article.push(obj)
        } else {
          modify_supplier_article.push(obj)
        }
      }
      for (const i in modify.Children.supplier_bank_pic) {
        const obj = modify.Children.supplier_bank_pic[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_supplier_bank_pic.push(obj)
        } else {
          modify_supplier_bank_pic.push(obj)
        }
      }

      add.Children.supplier_brand = add_supplier_brand
      add.Children.supplier_bank_account = add_supplier_bank_account
      add.Children.supplier_article = add_supplier_article
      add.Children.supplier_bank_pic = add_supplier_bank_pic

      modify.Children.supplier_brand = modify_supplier_brand
      modify.Children.supplier_bank_account = modify_supplier_bank_account
      modify.Children.supplier_article = modify_supplier_article
      modify.Children.supplier_bank_pic = modify_supplier_bank_pic
      if (add_supplier_brand.length == 0 && add_supplier_bank_account.length == 0 && add_supplier_article.length == 0 && add_supplier_bank_pic.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    add_supplier_brand() {
      this.form.Children.supplier_brand.push({       //供应商经营品牌
        Supplier_Brand_SerialNumber: "",
        Supplier_SerialNumber: this.form.Supplier_SerialNumber,
        Brand_SerialNumber: '',
      })
    },
    remove_supplier_brand() {
      console.log(this.form.Children.supplier_brand.filter(item => item.Row_Status != '1').length);
      if (this.form.Children.supplier_brand.filter(item => item.Row_Status != '1').length > 1) {
        let i = this.form.Children.supplier_brand.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.supplier_brand.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.supplier_brand.pop()
        } else {
          this.$confirm('警告！此操作将删除一条数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.supplier_brand.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    add_supplier_bank_account() {
      this.form.Children.supplier_bank_account.push({       //供应商银行账号
        Supplier_Bank_Account_SerialNumber: "",
        Supplier_SerialNumber: this.form.Supplier_SerialNumber,
        Bank_Name: '',
        Account_Number: '',
      })
    },
    remove_supplier_bank_account() {
      if (this.form.Children.supplier_bank_account.filter(item => item.Row_Status != '1').length > 1) {
        let i = this.form.Children.supplier_bank_account.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.supplier_bank_account.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.supplier_bank_account.pop()
        } else {
          this.$confirm('警告！此操作将删除一条数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.supplier_bank_account.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    add_supplier_article() {
      this.form.Children.supplier_article.push({       //供应商可供商品
        Supplier_Article_SerialNumber: "",
        Supplier_SerialNumber: this.form.Supplier_SerialNumber,
        Article_SerialNumber: '',
      })
    },
    remove_supplier_article() {
      if (this.form.Children.supplier_article.filter(item => item.Row_Status != '1').length > 1) {
        let i = this.form.Children.supplier_article.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.supplier_article.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.supplier_article.pop()
        } else {
          this.$confirm('警告！此操作将删除一条数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.supplier_article.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },

    // 省份 市 县联动
    selectProvinceFun(event) {
      console.log(event)
      if (event) {
        this.cityList = event.children
      } else {
        this.cityList = []
      }
      this.areaList = []
    },
    selectCityFun(event) {
      console.log(event)
      if (event) {
        this.areaList = event.children
      } else {
        this.areaList = []
      }
    },
    selectAreaFun(event) {
      if (event) {
        console.log(event)
        console.log(this.selectProvince, this.selectCity, this.selectArea);
        this.isdisabled = false
      } else {
        this.isdisabled = true
      }
    },
    selectAddress(event) {
      if (event && event != '' && this.selectArea.label != undefined) {
        this.form.Supplier_Address = this.selectProvince.label + '/'
          + this.selectCity.label + '/'
          + this.selectArea.label + '/'
          + this.address
      }
    }
  }
})